/**
 * 分帧加载管理器
 * 用于渐进式添加模型到场景中，避免一次性加载大量模型导致的卡顿
 */
export class FrameLoader {
    constructor() {
        this.pendingObjects = []; // 待添加的对象队列
        this.isLoading = false;   // 是否正在加载
        this.batchSize = 3;       // 每帧添加的对象数量
        this.frameDelay = 1;      // 帧延迟（每N帧添加一批）
        this.frameCount = 0;      // 帧计数器
        this.onProgress = null;   // 进度回调
        this.onComplete = null;   // 完成回调
        this.totalObjects = 0;    // 总对象数量
        this.loadedObjects = 0;   // 已加载对象数量
        
        // 性能监控
        this.startTime = 0;
        this.lastFrameTime = 0;
        this.performanceThreshold = 16; // 16ms = 60fps
        
        // 自适应调整
        this.adaptiveMode = true;
        this.minBatchSize = 1;
        this.maxBatchSize = 10;
    }
    
    /**
     * 添加对象到加载队列
     * @param {Object} object - 要添加的对象
     * @param {Object} options - 添加选项
     */
    addToQueue(object, options = {}) {
        const queueItem = {
            object: object,
            priority: options.priority || 0,
            delay: options.delay || 0,
            onAdd: options.onAdd || null,
            metadata: options.metadata || {}
        };
        
        this.pendingObjects.push(queueItem);
        this.totalObjects++;
        
        // 按优先级排序
        this.pendingObjects.sort((a, b) => b.priority - a.priority);
        
        // 如果当前没有在加载，开始加载
        if (!this.isLoading) {
            this.startLoading();
        }
    }
    
    /**
     * 开始加载过程
     */
    startLoading() {
        this.isLoading = true;
        this.startTime = performance.now();
        this.lastFrameTime = this.startTime;
        this.frameCount = 0;
        this.loadedObjects = 0;
        
        console.log(`FrameLoader: 开始加载 ${this.totalObjects} 个对象`);
    }
    
    /**
     * 更新加载过程（需要在渲染循环中调用）
     * @param {Function} addCallback - 添加对象的回调函数
     */
    update(addCallback) {
        if (!this.isLoading || this.pendingObjects.length === 0) {
            return;
        }
        
        this.frameCount++;
        
        // 检查帧延迟
        if (this.frameCount % this.frameDelay !== 0) {
            return;
        }
        
        // 性能自适应调整
        if (this.adaptiveMode) {
            this.adjustBatchSize();
        }
        
        // 处理当前批次的对象
        const currentTime = performance.now();
        const batchStartTime = currentTime;
        let objectsAdded = 0;
        
        console.log(`FrameLoader update: processing batch, pending: ${this.pendingObjects.length}, batchSize: ${this.batchSize}`);
        
        while (this.pendingObjects.length > 0 && objectsAdded < this.batchSize) {
            const queueItem = this.pendingObjects.shift();
            
            // 检查延迟
            if (queueItem.delay > 0) {
                const elapsed = currentTime - this.startTime;
                if (elapsed < queueItem.delay) {
                    // 重新放回队列末尾
                    this.pendingObjects.push(queueItem);
                    console.log(`FrameLoader: object delayed, elapsed: ${elapsed}ms, delay: ${queueItem.delay}ms`);
                    break;
                }
            }
            
            try {
                console.log(`FrameLoader: adding object to scene:`, queueItem.object);
                
                // 调用添加回调
                if (addCallback) {
                    addCallback(queueItem.object);
                }
                
                // 执行对象特定的添加回调
                if (queueItem.onAdd) {
                    queueItem.onAdd(queueItem.object);
                }
                
                objectsAdded++;
                this.loadedObjects++;
                
                console.log(`FrameLoader: object added successfully, total loaded: ${this.loadedObjects}`);
                
                // 检查性能
                const batchTime = performance.now() - batchStartTime;
                if (batchTime > this.performanceThreshold) {
                    console.warn(`FrameLoader: 批次处理时间过长 ${batchTime.toFixed(2)}ms`);
                    break;
                }
                
            } catch (error) {
                console.error('FrameLoader: 添加对象时出错:', error, queueItem);
            }
        }
        
        // 更新进度
        if (this.onProgress) {
            const progress = this.totalObjects > 0 ? this.loadedObjects / this.totalObjects : 0;
            this.onProgress(progress, this.loadedObjects, this.totalObjects);
        }
        
        // 检查是否完成
        if (this.pendingObjects.length === 0) {
            this.complete();
        }
        
        this.lastFrameTime = currentTime;
    }
    
    /**
     * 自适应调整批次大小
     */
    adjustBatchSize() {
        const currentTime = performance.now();
        const frameTime = currentTime - this.lastFrameTime;
        
        if (frameTime > this.performanceThreshold) {
            // 性能下降，减少批次大小
            this.batchSize = Math.max(this.minBatchSize, this.batchSize - 1);
            this.frameDelay = Math.min(5, this.frameDelay + 1);
        } else if (frameTime < this.performanceThreshold * 0.5) {
            // 性能良好，增加批次大小
            this.batchSize = Math.min(this.maxBatchSize, this.batchSize + 1);
            this.frameDelay = Math.max(1, this.frameDelay - 1);
        }
    }
    
    /**
     * 完成加载
     */
    complete() {
        this.isLoading = false;
        const totalTime = performance.now() - this.startTime;
        
        console.log(`FrameLoader: 加载完成，共加载 ${this.loadedObjects} 个对象，耗时 ${totalTime.toFixed(2)}ms`);
        
        if (this.onComplete) {
            this.onComplete(this.loadedObjects, totalTime);
        }
    }
    
    /**
     * 清空队列
     */
    clear() {
        this.pendingObjects = [];
        this.isLoading = false;
        this.totalObjects = 0;
        this.loadedObjects = 0;
        console.log('FrameLoader: 队列已清空');
    }
    
    /**
     * 暂停加载
     */
    pause() {
        this.isLoading = false;
        console.log('FrameLoader: 加载已暂停');
    }
    
    /**
     * 恢复加载
     */
    resume() {
        if (this.pendingObjects.length > 0) {
            this.startLoading();
        }
    }
    
    /**
     * 设置配置
     * @param {Object} config - 配置对象
     */
    setConfig(config) {
        if (config.batchSize !== undefined) {
            this.batchSize = Math.max(1, config.batchSize);
        }
        if (config.frameDelay !== undefined) {
            this.frameDelay = Math.max(1, config.frameDelay);
        }
        if (config.adaptiveMode !== undefined) {
            this.adaptiveMode = config.adaptiveMode;
        }
        if (config.minBatchSize !== undefined) {
            this.minBatchSize = Math.max(1, config.minBatchSize);
        }
        if (config.maxBatchSize !== undefined) {
            this.maxBatchSize = Math.max(this.minBatchSize, config.maxBatchSize);
        }
        if (config.performanceThreshold !== undefined) {
            this.performanceThreshold = Math.max(1, config.performanceThreshold);
        }
    }
    
    /**
     * 获取状态信息
     */
    getStatus() {
        return {
            isLoading: this.isLoading,
            pendingCount: this.pendingObjects.length,
            loadedCount: this.loadedObjects,
            totalCount: this.totalObjects,
            progress: this.totalObjects > 0 ? this.loadedObjects / this.totalObjects : 0,
            batchSize: this.batchSize,
            frameDelay: this.frameDelay
        };
    }
    
    /**
     * 设置进度回调
     * @param {Function} callback - 进度回调函数
     */
    setProgressCallback(callback) {
        this.onProgress = callback;
    }
    
    /**
     * 设置完成回调
     * @param {Function} callback - 完成回调函数
     */
    setCompleteCallback(callback) {
        this.onComplete = callback;
    }
}
